<?php
// This class handles emails
// Email settings can be changed here

require_once("phpmailer/class.phpmailer.php");

class Email
{
	private $host = "localhost"; // this mainly affect image links, change when host server changes
	private $error = "";
	private $setting = array(); // smtp settings
	public static $VIEW_UPLOAD=0;
	
	/**
	 * Constructor for Email class
	 */
	public function Email() {
		$resultset = EmailSet::model()->getSMTPSetting();
		// Gets settings from db model
		foreach ($resultset as $record) {
    		$this->setting[$record['name']] = $record['value'];
		}
	}
	
	/**
	 * Description: This method sets the phpmailer parameters and uses the object to send email
	 * Returns: True if email has been sent; False otherwise
	 */
	public function sendEmail($to, $from_name, $subject, $templateID, $data = array()) {
		$mail = new PHPMailer();
		$mail->IsSMTP(); // send via SMTP
		$mail->SMTPDebug = 0;
		$mail->SMTPAuth = true; // turn on SMTP authentication
		$mail->SMTPSecure = 'ssl';
		$mail->Host = $this->setting['host'];
		$mail->Port = $this->setting['port'];
		$mail->Username = $this->setting['user_name']; // SMTP username
		$mail->Password = $this->setting['password']; // SMTP password
		$mail->SetFrom($this->setting['user_name'], $from_name); // (FROM, FROM_NAME)
		$mail->AddAddress($to); //name as optional 2nd arg
		$mail->IsHTML(true); // send as HTML
		$mail->Subject = $subject;
		$mail->Body = $this->getTemplate($templateID, $data); //HTML Body
		
		if(!$mail->Send()) {
			$this->error = $mail->ErrorInfo;
			return false;
		}
		else {
			$this->error = "Message has been sent";
			return true;
		}
	}
	
	/**
	 * Description: This method determines what email template to use depending on the templateID and 
	 * makes a call to other functions to update the template email values
	 * Returns: Email source code as string
	 */
	public function getTemplate($templateID, $data) {
		$template_path;
	    if ($templateID == self::$VIEW_UPLOAD) {
	        $template_path = "templates/view-upload-file.html";
	        
	    }
	    $htmlFile = file_get_contents($template_path, 1);
	    $htmlFile = $this->replaceDataInEmail($htmlFile, $data);
		return $htmlFile;
	}

	/*
	 * Description: This method replaces placeholders for the BUYER CLOSE template with appropriate values
	 * Returns: The email source code as string
	 * Note: BUYER CLOSE template corresponds to a buyer closing an order. This email is intended for the supplier.
	 */
	public function replaceDataInEmail($htmlFile, $data) {
		foreach(array_keys($data) as $key)
		{
			$htmlFile = str_replace('['.$key.']', $data[$key], $htmlFile);
		}
		return $htmlFile;
	}

	public function getError() {
		return $this->error;
	}
}
?>